import 'dart:async';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jicaimao_flutter/entity/loginbean.dart';
import 'package:jicaimao_flutter/event/register_event.dart';
import 'package:jicaimao_flutter/utils/api_address.dart';
import 'package:jicaimao_flutter/utils/event_bus.dart';
import 'package:jicaimao_flutter/utils/http_utils.dart';
import 'package:jicaimao_flutter/utils/string_utils.dart';
import 'package:jicaimao_flutter/widget/app_bar.dart';

class RegisterConfirmPage extends StatefulWidget {
  @override
  _RegisterConfirmPageState createState() => _RegisterConfirmPageState();
  String mobile;
  String verificationCode;
  RegisterConfirmPage({this.mobile, this.verificationCode});
}

class _RegisterConfirmPageState extends State<RegisterConfirmPage> {
  bool psw_noshow = true;
  bool isRegister = false;
  final password_controller = TextEditingController();
  EventBus eventBus= new EventBus();
  StreamSubscription listen;
  _RegisterConfirmPageState(){
    listen =  eventBus.on<RegisterEvent>().listen((event) {
      // All events are of type UserLoggedInEvent (or subtypes of it).
      Navigator.pop(context);
    });
  }
  @override
  void dispose() {
    listen?.cancel();
    super.dispose();
  }

  _register(){
    if(!isRegister){
      return;
    }
    String psw = password_controller.text;
    if(psw.isEmpty){
      showToast( "请输入密码");
      return;
    }
    if(!StringUtils.checkAccountMarkNmu(psw)){
      showToast( "密码为6-18位数字和字母");
      return;
    }
    setState(() {
      isRegister = !isRegister;
    });
    _registerLoadData(psw);
  }
  _registerLoadData(String psw) async{
//    print("key=${userId}");
    var data = {'verificationCode': widget.verificationCode, "mobile": widget.mobile, "password": psw};
    var respone = await HttpUtil().post(NetAddress.register, data: data);

    Loginbean loginBean = Loginbean.fromJson(json.decode(respone));
    if (loginBean.code == "200") {
//      print(loginBean.result.userId);
      showToast( loginBean.msg);
//      Navigator.pop(context);
      eventBus.fire(RegisterEvent());
    } else {
      showToast( loginBean.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        backgroundColor: Color(0xfffafafa),
        appBar: AppBarNormal("注册确认"),
        body: new SingleChildScrollView(
          child: new ConstrainedBox(
            constraints: new BoxConstraints(
              minHeight: 120.0,
            ),
            child: Container(
              margin: EdgeInsets.fromLTRB(20, 50, 20, 0),
              child: Column(
                children: <Widget>[
                  _inputPassword(),

                  GestureDetector(
                    onTap: _register,
                    child: Container(
                        margin: EdgeInsets.only(top: 40),
                        decoration: new BoxDecoration(
                            color:
                            isRegister ? Color(0xffad5afe) : Color(0xffD4d4d4),
                            borderRadius: BorderRadius.circular(3.0)),
                        alignment: Alignment.center,
                        height: 40,
                        width: double.infinity,
                        child: Text(
                          "完成",
                          style: TextStyle(color: Colors.white),
                        )),
                  ),
                ],
              ),
            ),
          ),
        ));
  }

  _inputPassword() {
    return Container(
        height: 40,
        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
        color: Color(0xfff7f7f7),
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 1,
              child: TextField(
                controller: password_controller,
                keyboardType: TextInputType.text,
                onChanged: (text) {
                  String pPassWord = password_controller.text;
                  bool loginEnd = false;
                  if (pPassWord.isNotEmpty &&
                      widget.mobile.isNotEmpty &&
                      RegexUtil.isMobileExact(widget.mobile) &&
                      StringUtils.checkAccountMarkNmu(pPassWord)) {
                    loginEnd = true;
                  } else {
                    loginEnd = false;
                  }
                  setState(() {
                    if (loginEnd) {
                      isRegister = true;
                    } else {
                      isRegister = false;
                    }
                  });
                },
                maxLines: 1,
                obscureText: psw_noshow,
                decoration: InputDecoration(
                    hasFloatingPlaceholder: false,
                    border: InputBorder.none,
                    hintText: '请输入密码(6-18位数字和字母)',
                    counterText: '',

                    ///限制最大长度后
                    disabledBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none),
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16.0,
                ),
              ),
            ),
            GestureDetector(
              child: Container(
                  width: 40,
                  height: 40,
                  padding: EdgeInsets.all(10),
                  child: Image.asset(psw_noshow
                      ? 'images/ps_notsee.png'
                      : 'images/ps_see.png')),
              onTap: () {
                setState(() {
                  psw_noshow = !psw_noshow;
                });
              },
            )
          ],
        ));
  }

  void showToast(String tipMsg) {
    Fluttertoast.showToast(
        msg: tipMsg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIos: 1,
        backgroundColor: Colors.black87,
        textColor: Colors.white,
        fontSize: 16.0);
  }
}
